<?php
/**
 * token token体系基础类
 * User: blue
 * Date: 2018/8/4 16:53
 */

namespace app\api\server;


use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\ParamException;
use app\lib\serverLib\Security;
use think\Exception;
use think\facade\Request;

class BaseToken
{
    /**
     * 生成token随机字符串
     * @return string
     */
    protected function productToken(){
        // 随机字符串+salt+时间戳 MD5生成token
        $randStr=Security::makeRandomStr(32);
        $salt=config('secure.salt');
        $t=$_SERVER['REQUEST_TIME'];
        $token=md5($randStr.$salt.$t);
        return $token;
    }

    /**
     * 获取token中指定的信息
     * @param string $key
     */
    protected function getTokenInfo($key){
    //    从头部获取token->利用token从缓存中获取数据,->提取缓存中指定的key
        $token=Request::header('token');
        if(!$token){throw new ParamException(['message'=>'请传入token令牌']);}
        $info=cache($token);
        $info=json_decode($info);
        if(!$info){
            throw new ParamException(['message'=>"token令牌无效或已过期"]);
        }
        if(!array_key_exists($key,$info)){
            throw new Exception(['message'=>'token对应的信息不存在']);
        }
        return $info[$key];
    }
    /**
     * token存入缓存
     * @param $res token的数据
     * @param $token token随机字符串
     */
    protected function tokenToCache(array $res,$token){
        $expire=config('wx.token_expire');
        $res=json($res);
        cache($token,$res,$expire);
    }

    /**
     * 验证token是否有效
     * @param string $token
     * @return bool;
     */
    public function validToken($token){
        $result=cache($token);
        if($result){
            return true;
        }else{
            return false;
        }
    }

    /**
     * user用户权限检测
     * @return bool
     * @throws Exception
     * @throws ForbiddenException
     * @throws ParamException
     */
    public function userApprove(){
        $scope=$this->getTokenInfo('scope');
        if($scope!=ScopeEnum::USER){
            throw new ForbiddenException();
        }
        return true;
    }

    /**
     * super用户权限检测
     * @return bool
     * @throws Exception
     * @throws ForbiddenException
     * @throws ParamException
     */
    public function superApprove(){
        $scope=$this->getTokenInfo('scope');
        if($scope!=ScopeEnum::SUPER){
            throw new ForbiddenException();
        }
        return true;
    }

    /**
     * user super用户权限检测
     * @return bool
     * @throws Exception
     * @throws ForbiddenException
     * @throws ParamException
     */
    public function commonApprove(){
        $scope=$this->getTokenInfo('scope');
        if($scope==ScopeEnum::USER||$scope==ScopeEnum::SUPER){
            return true;
        }else{
            throw new ForbiddenException();
        }
    }


}